'use strict';

const passwordHash = require('yi-password-hash');
const middleware = (req, res, next) => {
    let doc = req.body;
    passwordHash.hash(doc.pwd, function (err, result) {
        if(err)return res.err.unknownError(err);
        doc.pwd = result;
        //next();
        req.mongo.collection("manager").find({mobile:req.body.mobile}).next(function(err,r){
            if(err)return res.err.errorMongo(err);

            if(r) {
                return res.reply({code:1002,message:"该手机号已经注册"});
                ////若此手机号已在系统中注册,直接返回此用户的ID,不能再次注册
                //return res.reply({_id: r._id});
            }else
                return next();
        })
    })
};

const handler = (req, res, next) => {
    const doc={};
    let keys = Object.keys(req.body);
    keys = keys.sort();
    keys.forEach(function (key) {
        doc[key] = req.body[key];
    });

    req.mongo.collection("manager").insertOne(doc, (err, result) => {
        if (err) return res.err.mongoError(err);
        res.reply({code:0,_id: result.insertedId});

    });
};
module.exports = {
    open:false,
    description:'新增管理员',
    middleware: middleware,
    handler: handler
};
